
package com.apes.fn.server.workDesk.repository;

import com.apes.fn.server.workDesk.model.VehicleControl;
import com.apes.framework.jpa.repository.CustomRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;


public interface VehicleControlRepository extends CustomRepository<VehicleControl, String> {

    @Query("SELECT A FROM VehicleControl A , FsmFlowInstance B,FsmState C\n" +
            " WHERE A.id = B.businessKey AND B.currentState = C.id AND B.fsmFlow = '000583' AND C.id <> 'ZK000757' AND A.dept.id = :deptId\n")
    List<VehicleControl> findNotOver(@Param("deptId") String deptId);

    @Query("SELECT A FROM VehicleControl A , FsmFlowInstance B,FsmState C\n" +
            " WHERE A.id = B.businessKey AND B.currentState = C.id AND B.fsmFlow = '000583' AND C.id = 'ZK000756' \n")
    List<VehicleControl> findNotOver();

    @Query("SELECT A FROM VehicleControl A , FsmFlowInstance B,FsmState C\n" +
            " WHERE A.id = B.businessKey AND B.currentState = C.id AND B.fsmFlow = '000583' AND C.id <> 'ZK000757' " +
            " AND A.createDate >= :startDate AND A.createDate <= :endDate\n")
    List<VehicleControl> findNotOver(@Param("startDate") Date startDate,@Param("endDate") Date endDate);

    @Modifying
    @Transactional
    @Query(
            value = "UPDATE VEHICLE_CONTROL A\n" +
                    "SET state   = 'ZK000758',\n" +
                    "    VERSION = VERSION + 1\n" +
                    "WHERE nvl(state, 'ZK000757')\n" +
                    "    <> 'ZK000758'\n" +
                    "  and exists(SELECT B.CURRENT_STATE\n" +
                    "             FROM FSM_FLOW_INST B\n" +
                    "             WHERE B.FSM_FLOW_ID = '000583'\n" +
                    "               AND A.ID = B.BUSINESS_KEY\n" +
                    "               and B.CURRENT_STATE = 'ZK000758')",
            nativeQuery = true
    )
    int updateVehicleControlState();
}

